package net.prasenjit.test.core.auth;

import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSSConfig;
import org.apache.ws.security.WSSecurityEngine;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.handler.RequestData;
import org.apache.ws.security.message.token.UsernameToken;
import org.apache.ws.security.validate.UsernameTokenValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

public class MyWSSConfig extends WSSConfig {

    @Autowired
    @Qualifier("org.springframework.security.authenticationManager")
    private ProviderManager providerManager;

    public MyWSSConfig() {
        setValidator(WSSecurityEngine.USERNAME_TOKEN, new MyUsernameTokenValidator());
        setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
    }

    class MyUsernameTokenValidator extends UsernameTokenValidator {

        @Override
        protected void verifyPlaintextPassword(UsernameToken usernameToken, RequestData data) throws WSSecurityException {
            Authentication authentication = new UsernamePasswordAuthenticationToken(usernameToken.getName(),
                    usernameToken.getPassword());
            try {
                authentication = providerManager.authenticate(authentication);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (AuthenticationException e) {
                throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
            }
        }

    }
}
